import logging
import time
import traceback

import requests
import mimetypes
from flask import jsonify
from flask import make_response
from dao.db_connect import db_connect as db
import controller.carbon_alipay.AlipayConfig as AlipayConfig

label_dic = {
    'city': 'city',
    'county': 'county',
    'emission_factors': 'emission factors',
    'global_countries': 'global countries',
    'input-output-tables': 'input-output-tables',
    'nation': 'nation',
    'process': 'process',
    'province': 'province',
    'remark-report': 'remark-report',
    'white-book': 'white-book',
}

success = 200  # 请求成功
# errors
identification_error = 100  # 未识别成功
internal_error = 500  # 服务器错误
data_missing = 101  # 数据库内无相关数据
usr_rank_error = 105  # 用户权限不足
download_times_leak = 106  # 下载次数不足


class GetFilesUrl(object):
    def __init__(self):
        print("GetFilesUrl init")

    @classmethod
    def get_ids(cls, request):
        """
        获取文件列表
        label：文件类别
        row_num: 每页行数
        page_num: 页号，从1开始
        """
        logging.debug("working on get_ids")
        msg = "获取列表成功"
        code = success

        label = request.values.get('label')
        row_num = request.values.get('row_num')
        if row_num is None or len(row_num) == 0:
            row_num = 15
        else:
            row_num = int(row_num)
            if row_num <= 0:
                row_num = 15
        page_num = request.values.get('page_num')
        if page_num is None or len(page_num) == 0:
            page_num = 1
        else:
            page_num = int(page_num)
            if page_num <= 0:
                page_num = 1

        if label is None or len(label) == 0:
            label = 'city'

        try:
            label_name = label_dic.get(label)
            if not label_name:
                msg = "标签不存在！"
                code = identification_error
                return jsonify(code=code, data=[], msg=msg)
            query_sql = f'select id, label, name, rank from files_info ' \
                        f'where label = "{label_name}" order by name'
            data = db.queryAll(query_sql)

            # 分页
            page_data = data[(page_num - 1) * row_num: page_num * row_num]

        except Exception as e:
            msg = "获取列表失败"
            code = data_missing
            logging.debug(traceback.format_exc())
            return jsonify(code=code, data=[], msg=msg)

        resp = {
            "code": code,
            "msg": msg,
            "data": page_data,
            'row_num': row_num,
            'page_num': page_num,
            "total": len(data)
        }
        return jsonify(resp)

    @classmethod
    def get_url(cls, request):
        """
        获取文件链接
        """
        file_data = {}
        logging.debug("working on get_url")
        msg = "获取链接成功"
        code = success

        file_id = request.values.get('file_id')
        user_id = request.values.get('user_id')
        if file_id is None or len(file_id) == 0:
            msg = "无法获取输入的文件ID"
            resp = {
                "code": data_missing,
                "msg": msg,
                "data": {}
            }
            return jsonify(resp)

        try:
            query_sql = f'select id, rank, vip_expire, last_expire_time, max_times, current_times ' \
                        f'from user where id = "{user_id}"'

            user_data = db.queryOne(query_sql)
            user_rank = user_data['rank']
            vip_expire = user_data['vip_expire']
            if vip_expire is not None:
                string_vip_expire = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(vip_expire))
                logging.debug("vip_expire:" + str(string_vip_expire))

            query_sql = f'select url, label, name, rank from files_info where id = "{file_id}"'
            file_data = db.queryOne(query_sql)
            file_rank = file_data['rank']

            query_sql = f'select uid, fid from files_purchased where fid = "{file_id}" and uid = "{user_id}"'
            file_purchase = db.queryOne(query_sql)

            # 用户下载权限不足
            if file_purchase is None and user_rank < file_rank:
                return jsonify(code=usr_rank_error, data=None, msg='权限不足，该文件为VIP专享文件！')

            # 用户会员过期
            if file_purchase is None and file_rank != 0 \
                    and vip_expire is not None and vip_expire < int(time.time()):
                if user_rank > 0:
                    # 刷新数据库
                    update_sql = f"update user set rank=0 where id='{user_id}'"
                    db.UpdateOrDeleteOrInsert(update_sql)
                return jsonify(code=usr_rank_error, data=None, msg='会员到期！')

            # 刷新用户可下载次数
            current = int(time.time())
            max_times = user_data.get('max_times')
            current_times = user_data.get('current_times')
            last_expire_time = user_data.get('last_expire_time')
            if max_times is None:
                max_times = AlipayConfig.default_download_max_times
            if current_times is None:
                current_times = 0
            if last_expire_time is None:
                last_expire_time = current

            monthly_time = 30 * 24 * 3600
            if last_expire_time + monthly_time < current:
                max_times = AlipayConfig.default_download_max_times
                current_times = 0
                time_area = current - last_expire_time
                time_area = int(time_area / monthly_time)
                last_expire_time = last_expire_time + time_area * monthly_time
            # 刷新数据库
            update_sql = f"update user set last_expire_time={last_expire_time}, " \
                         f"max_times={max_times}, current_times={current_times} " \
                         f"where id='{user_id}'"
            db.UpdateOrDeleteOrInsert(update_sql)

            # 文件未购买 & 用户可下载次数不足
            # 查询该文件是否已经购买
            if file_purchase is None and file_rank != 0:
                # 用户可下载次数是否充足
                if current_times >= max_times:
                    return jsonify(code=download_times_leak, data=None, msg='用户下载次数不足！')
                current_times = current_times + 1

            # 刷新用户已下载次数
            update_sql = f"update user set current_times={current_times} where id='{user_id}'"
            db.UpdateOrDeleteOrInsert(update_sql)

            file_data['current_times'] = current_times
            file_data['max_times'] = max_times
        except Exception as e:
            msg = "获取列表失败"
            code = data_missing
            logging.debug(traceback.format_exc())

        resp = {
            "code": code,
            "msg": msg,
            "data": file_data
        }
        return jsonify(resp)

    # @classmethod
    # def test_get_file(cls, request):
    #     try:
    #         url = request.values.get('url')
    #         if url is None or len(url) == 0:
    #             msg = "请求的种类不存在，请更换种类！"
    #             code = identification_error
    #             return jsonify(code=code, data={}, msg=msg)
    #
    #         r = requests.get(url, timeout=500)
    #         if r.status_code != 200:
    #             raise Exception("Cannot connect with oss server or file is not existed")
    #         response = make_response(r.content)
    #         mime_type = mimetypes.guess_type(url)[0]
    #
    #         response.headers['Content-Type'] = mime_type
    #         response.headers['Content-Disposition'] = 'attachment; filename={}'.format(
    #             url.encode().decode('latin-1'))
    #         return response
    #     except Exception as err:
    #         print('download_file error: {}'.format(str(err)))
    #         logging.exception(err)
    #         msg = "文件请求失败"
    #         code = data_missing
    #         return jsonify(code=code, data={}, msg=msg)
